package com.winglish.as3.exam.toeicspeaking 
{
	import com.winglish.as3.exam.toeicspeaking.vo.TSCommonVo;
	import com.winglish.as3.loader.ImgGroup;
	import com.winglish.as3.loader.SoundPlay;
	import com.winglish.as3.record.Recorder;
	import com.winglish.as3.utils.NumberUtil;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.events.MouseEvent;
	import flash.utils.Timer;
	/**
	 * ...
	 * @author charmjin
	 */
	public class TSCommon extends TSCommonVo
	{
		protected var partNo:int;
		private var soundLoaded:Boolean = false;
		private var imgLoaded:Boolean = true;
		private var soundTLen:uint = 0;
		private var soundLoadLen:uint = 0;
		
		protected var d_sound:SoundPlay;	//direction sound
		protected var q_sound:Array = new Array();	//question sound
		protected var a_sound:Array = new Array();	//answer sound
		protected var preparingSound:SoundPlay;
		protected var readingSound:SoundPlay;	
		protected var speakingSound:SoundPlay;
		protected var answeringSound:SoundPlay;
		protected var img:ImgGroup;
		protected var record:Array = new Array();
		
		protected var count:int = 0;
		private var timer:Timer;
		protected var mcRoot:MovieClip;	
		protected var mcParent:MovieClip;	//최상위(sceen)
		private var sec:int;
		private var isRec:Boolean = false;
		
		public function TSCommon(no:int) 
		{
			partNo = no;
			timer = new Timer(1000);
			timer.addEventListener(TimerEvent.TIMER, timerIng);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerComplete);
		}
		
		/**
		 * 관련 모든 사운드 로드
		 * @param	soundPath
		 * @param	q_soundFile
		 * @param	a_soundFile
		 */
		protected function soundLoad(soundPath:String, q_soundFile:Array, a_soundFile:Array):void {
			for (var i:uint = 0; i < TSData["PART"+partNo+"_LOAD"].length; i++) {
				switch(TSData["PART"+partNo+"_LOAD"][i]) {
					case TSData.PART : //direction
						d_sound = new SoundPlay();	
						soundAddEvent(d_sound);
						d_sound.soundLoader(soundPath + TSData["PART"+partNo+"_DIRECTION_FILE"]);
						break;
					case TSData.PREPARING : //preparing
						preparingSound = new SoundPlay();
						soundAddEvent(preparingSound);
						preparingSound.soundLoader(soundPath + TSData.PREPARING_FILE);
						break;
					case TSData.READING : //reading
						readingSound = new SoundPlay();
						soundAddEvent(readingSound);
						readingSound.soundLoader(soundPath + TSData.READING_FILE);
						break;
					case TSData.SPEAKING : //speaking
						speakingSound = new SoundPlay();
						soundAddEvent(speakingSound);
						speakingSound.soundLoader(soundPath + TSData.SPEAKING_FILE);
						break;
					case TSData.ANSWERING : //answering
						answeringSound = new SoundPlay();
						soundAddEvent(answeringSound);
						answeringSound.soundLoader(soundPath + TSData.ANSWERING_FILE);
						break;
				}
			}
			
			for (i = 0; i < q_soundFile.length; i++) {
				q_sound[i] = new SoundPlay();
				soundAddEvent(q_sound[i]);
				q_sound[i].soundLoader(soundPath + q_soundFile[i]);
			}
			
			for (i = 0; i < a_soundFile.length; i++) {
				a_sound[i] = new SoundPlay();
				soundAddEvent(a_sound[i]);
				a_sound[i].soundLoader(soundPath + a_soundFile[i]);
				record[i] = new Recorder();
			}
		}
		
		/**
		 * sound add event
		 * sound 로드하기 전에 이벤트 등록 먼저 한다.
		 * @param	sound
		 */
		private function soundAddEvent(sound:SoundPlay):void {
			sound.addEventListener("loadComplete", soundLoadComplete);
			sound.addEventListener(Event.SOUND_COMPLETE, soundPlayComplete);
			soundTLen++;
		}
		
		/**
		 * sound load complete event
		 * @param	e
		 */
		private function soundLoadComplete(e:Event):void {
			soundLoadLen++;
			if (soundTLen == soundLoadLen) {
				soundLoaded = true;
				if (soundLoaded && imgLoaded) loadComplete();
			}
			e.currentTarget.removeEventListener("loadComplete", soundLoadComplete);
		}
		
		/**
		 * sound play complete event
		 * @param	e
		 */
		private function soundPlayComplete(e:Event):void {
			timerGap(true);
		}
		
		/**
		 * 관련 이미지 모두 로드(part2,4)
		 * @param	imgPath
		 * @param	imgFile
		 */
		protected function imgLoad(imgPath:String, imgFile:Array):void {
			if (imgFile.length > 0) {
				img = new ImgGroup(imgFile, imgPath);
				img.addEventListener("imgAllLoad", imgLoadComplete);
			}else {
				imgLoaded = true;
				if (soundLoaded && imgLoaded) loadComplete();
			}
		}
		
		/**
		 * img load complete
		 * @param	e
		 */
		private function imgLoadComplete(e:Event):void {
			imgLoaded = true;
			if (soundLoaded && imgLoaded) loadComplete();
			img.removeEventListener("imgAllLoad", imgLoadComplete);
		}
		
		/**
		 * 사운드와 이미지 모두 로드
		 */
		private function loadComplete():void {
			dispatchEvent(new Event("TSAllLoad"));
		}
		
		
		/**
		 * 테스트 진행(사운드 플레이, 녹음, 공백시간)
		 */
		protected function tsSoundPlay():void {
			if (count < TSData["PART" + partNo].length) {
				var str:String = TSData["PART" + partNo][count];
				switch(typeof TSData["PART" + partNo][count]) {
					case "string" : 
						if (str.indexOf("_Sound") != -1) {	//공통 사운드 플레이
							switch(str) {
								case TSData.PART : 
									d_sound.soundPlay();
									break;
								case TSData.PREPARING :
									preparingSound.soundPlay();
									break;
								case TSData.READING :
									readingSound.soundPlay();
									break;
								case TSData.SPEAKING :
									speakingSound.soundPlay();
									break;
								case TSData.ANSWERING :
									answeringSound.soundPlay();
									break;
							}
						}else if (str.indexOf("sound") == 0) {	//문제 사운드 플레이
							q_sound[int(str.substr( -1))].soundPlay();
							
						}else {	//녹음
							timer.repeatCount = int(str.split("r")[0]);
							sec = timer.repeatCount;
							timer.start();
							isRec = true;
							record[int(str.split("r")[1])].start();
						}
						break;
					case "number" :	//공백 시간 텀
						timer.repeatCount = int(str);
						sec = timer.repeatCount;
						timer.start();
						break;
				}
			}
			
			
		}
		
		/**
		 * timer ing event
		 * @param	e
		 */
		private function timerIng(e:TimerEvent):void {
			sec--;
			secTxt.text = NumberUtil.itostr(sec);
		}
		
		/**
		 * timer complete event
		 * @param	e
		 */
		private function timerComplete(e:TimerEvent):void {
			timer.reset();
			secTxt.text = "00";
			if (isRec) {
				record[int(TSData["PART" + partNo][count].split("r")[1])].stop();
				isRec = false;
			}
			timerGap(true);
		}
	
		/**
		 * 사운드재생, 녹음, 공백시간 등이 끝나고 나서 간격 
		 */
		private function timerGap(boo:Boolean):void {
			var gapTimer:Timer = new Timer(1000, TSData.TIMER_GAP);
			gapTimer.addEventListener(TimerEvent.TIMER_COMPLETE, gapTimerComplete);
			gapTimer.start();
		}
		
		/**
		 * 간격 타이머 complete event
		 * @param	e
		 */
		private function gapTimerComplete(e:TimerEvent):void {
			count++;
			dispatchEvent(new Event("soundPlayComplete"));
			tsSoundPlay();
		}
		
		/**
		 * 모범답변 페이지로 이동하는 버튼 셋팅.
		 */
		protected function goAnswerSet():void {
			if (mcParent.resMc) {
				mcParent.resMc.nextBtn.addEventListener(MouseEvent.CLICK, nextBtnClick);
			}
		}
		
		
		/**
		 * possible answer btn click event
		 * @param	e
		 */
		private function nextBtnClick(e:MouseEvent):void {
			if (mcParent.resMc) {
				mcParent.resMc.gotoAndStop(2);
				mcParent.resMc.resBtn.addEventListener(MouseEvent.CLICK, resBtnClick);
				mcParent.resMc.cancelBtn.addEventListener(MouseEvent.CLICK, cancelBtnClick);
			}
		}
		/**
		 * possible answer ok btn click event
		 * @param	e
		 */
		private function resBtnClick(e:MouseEvent):void {
			mcParent.resMc.resBtn.removeEventListener(MouseEvent.CLICK, resBtnClick);
			mcParent.resMc.cancelBtn.removeEventListener(MouseEvent.CLICK, cancelBtnClick);
			
			var str:String = TSData["PART" + partNo][count];
			switch(typeof TSData["PART" + partNo][count]) {
				case "string" : 
					if (str.indexOf("_Sound") != -1) {	//사운드 플레이
						switch(str) {
							case TSData.PART : 
								d_sound.soundStop();
								break;
							case TSData.PREPARING :
								preparingSound.soundStop();
								break;
							case TSData.READING :
								readingSound.soundStop();
								break;
							case TSData.SPEAKING :
								speakingSound.soundStop();
								break;
							case TSData.ANSWERING :
								answeringSound.soundStop();
								break;
						}
					}else {	//녹음
						timer.stop();
						timer.reset();
						isRec = false;
						record[int(str.split("r")[1])].stop();
					}
					break;
				case "number" :	//공백 시간 텀
					timer.stop();
					timer.reset();
					break;
			}
			count = TSData["PART" + partNo].length;
			dispatchEvent(new Event("soundPlayComplete"));
			
		}
		
		/**
		 * possible answer no btn click event
		 * @param	e
		 */
		private function cancelBtnClick(e:MouseEvent):void {
			mcParent.resMc.gotoAndStop(1);
		}
		
		/**
		 * reset
		 */
		protected function reset():void {
			count = 0;
			timer.reset();
			for (var i:uint = 0; i < record.length; i++) {
				record[i] = new Recorder();
			}
			tsSoundPlay();
		}
	}

}